

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="Blue~u~u~u">
  <meta name="author" content="Blue~u~u~u">
  <meta name="keywords" content="">
  <meta name="description" content="ES &amp; SpringData ES高级客户端创建项目 elasticsearch-demo 导入pom文件，ES依赖的版本最好和客户端对应 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849&lt;parent&gt;       &lt;groupId&gt;">
<meta property="og:type" content="article">
<meta property="og:title" content="ElasticSearch-高级客户端">
<meta property="og:url" content="http://www.slx.blue/2022/01/11/ElasticSearch/index.html">
<meta property="og:site_name" content="Blue~u~u~u~u">
<meta property="og:description" content="ES &amp; SpringData ES高级客户端创建项目 elasticsearch-demo 导入pom文件，ES依赖的版本最好和客户端对应 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849&lt;parent&gt;       &lt;groupId&gt;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s001.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s002.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s003.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s004.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s005.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s006.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s007.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s008.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s009.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s010.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s011.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s012.png">
<meta property="og:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s013.png">
<meta property="article:published_time" content="2022-01-11T09:19:31.000Z">
<meta property="article:modified_time" content="2022-01-11T09:24:57.845Z">
<meta property="article:author" content="Blue~u~u~u">
<meta property="article:tag" content="elasticsearch">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://www.slx.blue/2022/01/11/ElasticSearch/s001.png">
  
  <title>ElasticSearch-高级客户端 - Blue~u~u~u~u</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"www.slx.blue","root":"/","version":"1.8.12","typing":{"enable":true,"typeSpeed":180,"cursorChar":"_","loop":true},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname"}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>

<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"/>
<script src="/live2d-widget/autoload.js"></script>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Blue~u~u</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/images/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="ElasticSearch-高级客户端">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-01-11 17:19" pubdate>
        2022年1月11日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      43k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      135 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">ElasticSearch-高级客户端</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：5 个月前
                
              </p>
            
            <div class="markdown-body">
              <h1 id="ES-amp-SpringData-ES"><a href="#ES-amp-SpringData-ES" class="headerlink" title="ES &amp; SpringData ES"></a>ES &amp; SpringData ES</h1><h2 id="高级客户端"><a href="#高级客户端" class="headerlink" title="高级客户端"></a><a href="#%E9%AB%98%E7%BA%A7%E5%AE%A2%E6%88%B7%E7%AB%AF">高级客户端</a></h2><p>创建项目 <code>elasticsearch-demo</code></p>
<p>导入pom文件，ES依赖的版本最好和客户端对应</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">parent</span>&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.2.1.RELEASE<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">relativePath</span>/&gt;</span> <span class="hljs-comment">&lt;!-- lookup parent from repository --&gt;</span><br>   <span class="hljs-tag">&lt;/<span class="hljs-name">parent</span>&gt;</span><br><br>   <span class="hljs-tag">&lt;<span class="hljs-name">properties</span>&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">project.build.sourceEncoding</span>&gt;</span>UTF-8<span class="hljs-tag">&lt;/<span class="hljs-name">project.build.sourceEncoding</span>&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">project.reporting.outputEncoding</span>&gt;</span>UTF-8<span class="hljs-tag">&lt;/<span class="hljs-name">project.reporting.outputEncoding</span>&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">java.version</span>&gt;</span>1.8<span class="hljs-tag">&lt;/<span class="hljs-name">java.version</span>&gt;</span><br>   <span class="hljs-tag">&lt;/<span class="hljs-name">properties</span>&gt;</span><br><br>   <span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>       <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br>       <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span><br>       <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br>       <span class="hljs-comment">&lt;!--引入es的坐标--&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.elasticsearch.client<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>elasticsearch-rest-high-level-client<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>7.7.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>       <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.elasticsearch.client<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>elasticsearch-rest-client<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>7.7.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>       <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>       <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.elasticsearch<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>elasticsearch<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>7.7.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>       <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br>       <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.alibaba<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>fastjson<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>           <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.2.4<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>       <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br>   <span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>1.在 <code>resource</code> 文件夹下面创建 <code>application.yml</code> 文件</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs yml"><span class="hljs-attr">elasticsearch:</span><br>  <span class="hljs-attr">host:</span> <span class="hljs-string">IP地址</span><br>  <span class="hljs-attr">port:</span> <span class="hljs-number">9200</span><br></code></pre></td></tr></table></figure>

<p>2.启动类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@SpringBootApplication</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ElasticsearchDemoApplication</span> </span>&#123;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;<br>        SpringApplication.run(ElasticsearchDemoApplication.class, args);<br>    &#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<p>3.创建 <code>com.atguigu.config.ElasticSearchConfig</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.atguigu.config;<br><br><span class="hljs-keyword">import</span> org.apache.http.HttpHost;<br><span class="hljs-keyword">import</span> org.elasticsearch.client.RestClient;<br><span class="hljs-keyword">import</span> org.elasticsearch.client.RestHighLevelClient;<br><span class="hljs-keyword">import</span> org.springframework.boot.context.properties.ConfigurationProperties;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;<br><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-meta">@ConfigurationProperties(prefix = &quot;elasticsearch&quot;)</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ElasticSearchConfig</span> </span>&#123;<br>    <span class="hljs-keyword">private</span> String host;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> port;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getHost</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> host;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setHost</span><span class="hljs-params">(String host)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.host = host;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getPort</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-keyword">return</span> port;<br>    &#125;<br><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPort</span><span class="hljs-params">(<span class="hljs-keyword">int</span> port)</span> </span>&#123;<br>        <span class="hljs-keyword">this</span>.port = port;<br>    &#125;<br><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> RestHighLevelClient <span class="hljs-title">client</span><span class="hljs-params">()</span></span>&#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> RestHighLevelClient(RestClient.builder(<br>                <span class="hljs-keyword">new</span> HttpHost(<br>                        host,<br>                        port,<br>                        <span class="hljs-string">&quot;http&quot;</span><br>                )<br>        ));<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>新建测试类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.atguigu.test;<br><br><span class="hljs-meta">@RunWith(SpringRunner.class)</span><br><span class="hljs-meta">@SpringBootTest</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ElasticsearchTest</span> </span>&#123;<br>    <span class="hljs-meta">@Autowired</span><br>    <span class="hljs-keyword">private</span> RestHighLevelClient client;<br> <br><br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="创建索引"><a href="#创建索引" class="headerlink" title="创建索引"></a><a href="#%E5%88%9B%E5%BB%BA%E7%B4%A2%E5%BC%95">创建索引</a></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 添加索引</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addIndex</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>&#123;<br>        <span class="hljs-comment">//1.使用client获取操作索引的对象</span><br>        IndicesClient indicesClient = client.indices();<br>        <span class="hljs-comment">//2.具体操作，获取返回值</span><br>        CreateIndexRequest createRequest = <span class="hljs-keyword">new</span> CreateIndexRequest(<span class="hljs-string">&quot;abc	&quot;</span>);<br>        CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);<br><br>        <span class="hljs-comment">//3.根据返回值判断结果</span><br>        System.out.println(response.isAcknowledged());<br><br>    &#125;<br></code></pre></td></tr></table></figure>

<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s001.png" srcset="/img/loading.gif" lazyload alt="s001"></p>
<h3 id="添加索引和映射"><a href="#添加索引和映射" class="headerlink" title="添加索引和映射"></a><a href="#%E6%B7%BB%E5%8A%A0%E7%B4%A2%E5%BC%95%E5%92%8C%E6%98%A0%E5%B0%84">添加索引和映射</a></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs java">    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 添加索引</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addIndexAndMapping</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>        <span class="hljs-comment">//1.使用client获取操作索引的对象</span><br>        IndicesClient indicesClient = client.indices();<br>        <span class="hljs-comment">//2.具体操作，获取返回值</span><br>        CreateIndexRequest createRequest = <span class="hljs-keyword">new</span> CreateIndexRequest(<span class="hljs-string">&quot;aaa&quot;</span>);<br>        <span class="hljs-comment">//2.1 设置mappings</span><br>        String mapping = <span class="hljs-string">&quot;&#123;\n&quot;</span> +<br>                <span class="hljs-string">&quot;      \&quot;properties\&quot; : &#123;\n&quot;</span> +<br>                <span class="hljs-string">&quot;        \&quot;address\&quot; : &#123;\n&quot;</span> +<br>                <span class="hljs-string">&quot;          \&quot;type\&quot; : \&quot;text\&quot;,\n&quot;</span> +<br>                <span class="hljs-string">&quot;          \&quot;analyzer\&quot; : \&quot;ik_max_word\&quot;\n&quot;</span> +<br>                <span class="hljs-string">&quot;        &#125;,\n&quot;</span> +<br>                <span class="hljs-string">&quot;        \&quot;age\&quot; : &#123;\n&quot;</span> +<br>                <span class="hljs-string">&quot;          \&quot;type\&quot; : \&quot;long\&quot;\n&quot;</span> +<br>                <span class="hljs-string">&quot;        &#125;,\n&quot;</span> +<br>                <span class="hljs-string">&quot;        \&quot;name\&quot; : &#123;\n&quot;</span> +<br>                <span class="hljs-string">&quot;          \&quot;type\&quot; : \&quot;keyword\&quot;\n&quot;</span> +<br>                <span class="hljs-string">&quot;        &#125;\n&quot;</span> +<br>                <span class="hljs-string">&quot;      &#125;\n&quot;</span> +<br>                <span class="hljs-string">&quot;    &#125;&quot;</span>;<br>        createRequest.mapping(mapping,XContentType.JSON);<br>        CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);<br>        <span class="hljs-comment">//3.根据返回值判断结果</span><br>        System.out.println(response.isAcknowledged());<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s002.png" srcset="/img/loading.gif" lazyload alt="s002"></p>
<h3 id="查询索引"><a href="#查询索引" class="headerlink" title="查询索引"></a><a href="#%E6%9F%A5%E8%AF%A2%E7%B4%A2%E5%BC%95">查询索引</a></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">  * 查询索引</span><br><span class="hljs-comment">  */</span><br> <span class="hljs-meta">@Test</span><br> <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">queryIndex</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>     IndicesClient indices = client.indices();<br>     GetIndexRequest getReqeust = <span class="hljs-keyword">new</span> GetIndexRequest(<span class="hljs-string">&quot;aaa&quot;</span>);<br>     GetIndexResponse response = indices.get(getReqeust, RequestOptions.DEFAULT);<br><br>     <span class="hljs-comment">//获取结果</span><br>     Map&lt;String, MappingMetaData&gt; mappings = response.getMappings();<br>     <span class="hljs-keyword">for</span> (String key : mappings.keySet()) &#123;<br>         System.out.println(key+<span class="hljs-string">&quot;:&quot;</span> + mappings.get(key).getSourceAsMap());<br>     &#125;<br> &#125;<br></code></pre></td></tr></table></figure>

<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s003.png" srcset="/img/loading.gif" lazyload alt="s003"></p>
<h3 id="删除索引"><a href="#删除索引" class="headerlink" title="删除索引"></a><a href="#%E5%88%A0%E9%99%A4%E7%B4%A2%E5%BC%95">删除索引</a></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 删除索引</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-meta">@Test</span><br>   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteIndex</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>       IndicesClient indices = client.indices();<br><br>       DeleteIndexRequest deleteRequest = <span class="hljs-keyword">new</span> DeleteIndexRequest(<span class="hljs-string">&quot;abc&quot;</span>);<br>       AcknowledgedResponse response = indices.delete(deleteRequest, RequestOptions.DEFAULT);<br><br>       System.out.println(response.isAcknowledged());<br><br>   &#125;<br></code></pre></td></tr></table></figure>

<h3 id="判断索引是否存在"><a href="#判断索引是否存在" class="headerlink" title="判断索引是否存在"></a><a href="#%E5%88%A4%E6%96%AD%E7%B4%A2%E5%BC%95%E6%98%AF%E5%90%A6%E5%AD%98%E5%9C%A8">判断索引是否存在</a></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 判断索引是否存在</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-meta">@Test</span><br>   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">existIndex</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>       IndicesClient indices = client.indices();<br><br>       GetIndexRequest getRequest = <span class="hljs-keyword">new</span> GetIndexRequest(<span class="hljs-string">&quot;aaa&quot;</span>);<br>       <span class="hljs-keyword">boolean</span> exists = indices.exists(getRequest, RequestOptions.DEFAULT);<br>       System.out.println(exists);<br><br>   &#125;<br></code></pre></td></tr></table></figure>

<h3 id="添加文档-使用map作为数据"><a href="#添加文档-使用map作为数据" class="headerlink" title="添加文档,使用map作为数据"></a><a href="#%E6%B7%BB%E5%8A%A0%E6%96%87%E6%A1%A3-%E4%BD%BF%E7%94%A8map%E4%BD%9C%E4%B8%BA%E6%95%B0%E6%8D%AE">添加文档,使用map作为数据</a></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 添加文档,使用map作为数据</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-meta">@Test</span><br>   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addDoc</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>       <span class="hljs-comment">//数据对象，map</span><br>       Map data = <span class="hljs-keyword">new</span> HashMap();<br>       data.put(<span class="hljs-string">&quot;address&quot;</span>,<span class="hljs-string">&quot;深圳宝安&quot;</span>);<br>       data.put(<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;尚硅谷&quot;</span>);<br>       data.put(<span class="hljs-string">&quot;age&quot;</span>,<span class="hljs-number">20</span>);<br><br><br>       <span class="hljs-comment">//1.获取操作文档的对象</span><br>       IndexRequest request = <span class="hljs-keyword">new</span> IndexRequest(<span class="hljs-string">&quot;aaa&quot;</span>).id(<span class="hljs-string">&quot;1&quot;</span>).source(data);<br>       <span class="hljs-comment">//添加数据，获取结果</span><br>       IndexResponse response = client.index(request, RequestOptions.DEFAULT);<br><br>       <span class="hljs-comment">//打印响应结果</span><br>       System.out.println(response.getId());<br>   &#125;<br></code></pre></td></tr></table></figure>

<p>创建 <code>com.atguigu.domain.Person</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>&#123;<br>    <span class="hljs-keyword">private</span> String id;<br>    <span class="hljs-keyword">private</span> String name;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;<br>    <span class="hljs-keyword">private</span> String address;<br>    <span class="hljs-comment">// 设置 set get 和tostring方法</span><br>&#125;    <br></code></pre></td></tr></table></figure>

<h3 id="添加文档-使用对象作为数据"><a href="#添加文档-使用对象作为数据" class="headerlink" title="添加文档,使用对象作为数据"></a><a href="#%E6%B7%BB%E5%8A%A0%E6%96%87%E6%A1%A3-%E4%BD%BF%E7%94%A8%E5%AF%B9%E8%B1%A1%E4%BD%9C%E4%B8%BA%E6%95%B0%E6%8D%AE">添加文档,使用对象作为数据</a></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 添加文档,使用对象作为数据</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-meta">@Test</span><br>   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addDoc2</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>       <span class="hljs-comment">//数据对象，javaObject</span><br>       Person p = <span class="hljs-keyword">new</span> Person();<br>       p.setId(<span class="hljs-string">&quot;2&quot;</span>);<br>       p.setName(<span class="hljs-string">&quot;硅谷2222&quot;</span>);<br>       p.setAge(<span class="hljs-number">30</span>);<br>       p.setAddress(<span class="hljs-string">&quot;北京昌平区&quot;</span>);<br><br>       <span class="hljs-comment">//将对象转为json</span><br>       String data = JSON.toJSONString(p);<br><br>       <span class="hljs-comment">//1.获取操作文档的对象</span><br>       IndexRequest request = <span class="hljs-keyword">new</span> IndexRequest(<span class="hljs-string">&quot;aaa&quot;</span>).id(p.getId()).source(data,XContentType.JSON);<br>       <span class="hljs-comment">//添加数据，获取结果</span><br>       IndexResponse response = client.index(request, RequestOptions.DEFAULT);<br><br>       <span class="hljs-comment">//打印响应结果</span><br>       System.out.println(response.getId());<br>   &#125;<br></code></pre></td></tr></table></figure>

<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s004.png" srcset="/img/loading.gif" lazyload alt="s004"></p>
<h3 id="修改文档"><a href="#修改文档" class="headerlink" title="修改文档"></a><a href="#%E4%BF%AE%E6%94%B9%E6%96%87%E6%A1%A3">修改文档</a></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs java"> <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 修改文档：添加文档时，如果id存在则修改，id不存在则添加</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateDoc</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br><span class="hljs-comment">//数据对象，javaObject</span><br>        Person p = <span class="hljs-keyword">new</span> Person();<br>        p.setId(<span class="hljs-string">&quot;2&quot;</span>);<br>        p.setName(<span class="hljs-string">&quot;硅谷&quot;</span>);<br>        p.setAge(<span class="hljs-number">30</span>);<br>        p.setAddress(<span class="hljs-string">&quot;北京昌平区&quot;</span>);<br><br>        <span class="hljs-comment">//将对象转为json</span><br>        String data = JSON.toJSONString(p);<br><br>        <span class="hljs-comment">//1.获取操作文档的对象</span><br>        IndexRequest request = <span class="hljs-keyword">new</span> IndexRequest(<span class="hljs-string">&quot;aaa&quot;</span>).id(p.getId()).source(data,XContentType.JSON);<br>        <span class="hljs-comment">//添加数据，获取结果</span><br>        IndexResponse response = client.index(request, RequestOptions.DEFAULT);<br><br>        <span class="hljs-comment">//打印响应结果</span><br>        System.out.println(response.getId());<br>    &#125;<br></code></pre></td></tr></table></figure>

<h3 id="根据id查询文档"><a href="#根据id查询文档" class="headerlink" title="根据id查询文档"></a><a href="#%E6%A0%B9%E6%8D%AEid%E6%9F%A5%E8%AF%A2%E6%96%87%E6%A1%A3">根据id查询文档</a></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 根据id查询文档</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">findDocById</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br><br>        GetRequest getReqeust = <span class="hljs-keyword">new</span> GetRequest(<span class="hljs-string">&quot;aaa&quot;</span>,<span class="hljs-string">&quot;1&quot;</span>);<br>        <span class="hljs-comment">//getReqeust.id(&quot;1&quot;);</span><br>        GetResponse response = client.get(getReqeust, RequestOptions.DEFAULT);<br>        <span class="hljs-comment">//获取数据对应的json</span><br>        System.out.println(response.getSourceAsString());<br><br><br>    &#125;<br></code></pre></td></tr></table></figure>

<h3 id="根据id删除文档"><a href="#根据id删除文档" class="headerlink" title="根据id删除文档"></a><a href="#%E6%A0%B9%E6%8D%AEid%E5%88%A0%E9%99%A4%E6%96%87%E6%A1%A3">根据id删除文档</a></h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 根据id删除文档</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">delDoc</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>        DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);<br>        System.out.println(response.getId());<br>    &#125;<br></code></pre></td></tr></table></figure>

<h3 id="批量操作-脚本"><a href="#批量操作-脚本" class="headerlink" title="批量操作-脚本"></a>批量操作-脚本</h3><p>Bulk 批量操作是将文档的增删改查一些列操作，通过一次请求全都做完。减少网络传输次数。</p>
<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s005.png" srcset="/img/loading.gif" lazyload></p>
<figure class="highlight vala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs vala">GET person/_search<br><br><span class="hljs-meta"># 批量操作</span><br><span class="hljs-meta"># 1 删除1号记录</span><br><span class="hljs-meta"># 2 添加8号记录</span><br><span class="hljs-meta"># 3 修改2号记录 名称为二号</span><br><br>POST _bulk<br>&#123;<span class="hljs-string">&quot;delete&quot;</span>:&#123;<span class="hljs-string">&quot;_index&quot;</span>:<span class="hljs-string">&quot;person&quot;</span>,<span class="hljs-string">&quot;_id&quot;</span>:<span class="hljs-string">&quot;1&quot;</span>&#125;&#125;<br>&#123;<span class="hljs-string">&quot;create&quot;</span>:&#123;<span class="hljs-string">&quot;_index&quot;</span>:<span class="hljs-string">&quot;person&quot;</span>,<span class="hljs-string">&quot;_id&quot;</span>:<span class="hljs-string">&quot;8&quot;</span>&#125;&#125;<br>&#123;<span class="hljs-string">&quot;name&quot;</span>:<span class="hljs-string">&quot;8号&quot;</span>,<span class="hljs-string">&quot;age&quot;</span>:<span class="hljs-number">80</span>,<span class="hljs-string">&quot;address&quot;</span>:<span class="hljs-string">&quot;北京&quot;</span>&#125;<br>&#123;<span class="hljs-string">&quot;update&quot;</span>:&#123;<span class="hljs-string">&quot;_index&quot;</span>:<span class="hljs-string">&quot;person&quot;</span>,<span class="hljs-string">&quot;_id&quot;</span>:<span class="hljs-string">&quot;2&quot;</span>&#125;&#125;<br>&#123;<span class="hljs-string">&quot;doc&quot;</span>:&#123;<span class="hljs-string">&quot;name&quot;</span>:<span class="hljs-string">&quot;2号&quot;</span>&#125;&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">   * 1. 批量操作 bulk</span><br><span class="hljs-comment">   */</span><br>  <span class="hljs-meta">@Test</span><br>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testBulk</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>      <span class="hljs-comment">//创建bulkrequest对象，整合所有操作</span><br>      BulkRequest bulkRequest = <span class="hljs-keyword">new</span> BulkRequest();<br>      <span class="hljs-comment">/*</span><br><span class="hljs-comment">      # 1. 删除1号记录</span><br><span class="hljs-comment">      # 2. 添加6号记录</span><br><span class="hljs-comment">      # 3. 修改3号记录 名称为 “三号”</span><br><span class="hljs-comment">       */</span><br>      <span class="hljs-comment">//添加对应操作</span><br>      <span class="hljs-comment">//1. 删除1号记录</span><br>      DeleteRequest deleteRequest = <span class="hljs-keyword">new</span> DeleteRequest(<span class="hljs-string">&quot;person&quot;</span>,<span class="hljs-string">&quot;1&quot;</span>);<br>      bulkRequest.add(deleteRequest);<br><br>      <span class="hljs-comment">//2. 添加6号记录</span><br>      Map map = <span class="hljs-keyword">new</span> HashMap();<br>      map.put(<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;六号&quot;</span>);<br>      IndexRequest indexRequest = <span class="hljs-keyword">new</span> IndexRequest(<span class="hljs-string">&quot;person&quot;</span>).id(<span class="hljs-string">&quot;6&quot;</span>).source(map);<br>      bulkRequest.add(indexRequest);<br><br>      Map map2 = <span class="hljs-keyword">new</span> HashMap();<br>      map2.put(<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;三号&quot;</span>);<br>      <span class="hljs-comment">//3. 修改3号记录 名称为 “三号”</span><br>      UpdateRequest updateReqeust = <span class="hljs-keyword">new</span> UpdateRequest(<span class="hljs-string">&quot;person&quot;</span>,<span class="hljs-string">&quot;3&quot;</span>).doc(map2);<br>      bulkRequest.add(updateReqeust);<br><br>      <span class="hljs-comment">//执行批量操作</span><br>      BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);<br>      RestStatus status = response.status();<br>      System.out.println(status);<br>  &#125;<br></code></pre></td></tr></table></figure>

<h3 id="导入数据"><a href="#导入数据" class="headerlink" title="导入数据"></a><a href="#%E5%AF%BC%E5%85%A5%E6%95%B0%E6%8D%AE">导入数据</a></h3><p>将数据库中Goods表的数据导入到ElasticSearch中</p>
<p>① 将数据库中Goods表的数据导入到ElasticSearch中</p>
<p>② 创建索引</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><code class="hljs json">PUT goods<br>&#123;<br>	<span class="hljs-attr">&quot;mappings&quot;</span>: &#123;<br>		<span class="hljs-attr">&quot;properties&quot;</span>: &#123;<br>			<span class="hljs-attr">&quot;title&quot;</span>: &#123;<br>				<span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;text&quot;</span>,<br>				<span class="hljs-attr">&quot;analyzer&quot;</span>: <span class="hljs-string">&quot;ik_smart&quot;</span><br>			&#125;,<br>			<span class="hljs-attr">&quot;price&quot;</span>: &#123; <br>				<span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;double&quot;</span><br>			&#125;,<br>			<span class="hljs-attr">&quot;createTime&quot;</span>: &#123;<br>				<span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;date&quot;</span><br>			&#125;,<br>			<span class="hljs-attr">&quot;categoryName&quot;</span>: &#123;	<br>				<span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;keyword&quot;</span><br>			&#125;,<br>			<span class="hljs-attr">&quot;brandName&quot;</span>: &#123;	<br>				<span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;keyword&quot;</span><br>			&#125;,<br>			<span class="hljs-attr">&quot;spec&quot;</span>: &#123;		<br>				<span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;object&quot;</span><br>			&#125;,<br>			<span class="hljs-attr">&quot;saleNum&quot;</span>: &#123;	<br>				<span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;integer&quot;</span><br>			&#125;,<br>			<span class="hljs-attr">&quot;stock&quot;</span>: &#123;	<br>				<span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;integer&quot;</span><br>			&#125;<br>		&#125;<br>	&#125;<br>&#125;<br><br># 查询索引<br>GET goods<br></code></pre></td></tr></table></figure>

<ul>
<li>title:商品标题</li>
<li>price:商品价格</li>
<li>createTime:创建时间</li>
<li>categoryName:分类名称。如：家电，手机</li>
<li>brandName:品牌名称。如：华为，小米</li>
<li>spec: 商品规格。如： spec:{“屏幕尺寸”,“5寸”，“内存大小”,“128G”}</li>
<li>saleNum:销量</li>
<li>stock:库存量</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs mysql">create table `goods` (<br>	`id` double ,<br>	`title` varchar (300),<br>	`price` Decimal (22),<br>	`stock` double ,<br>	`saleNum` double ,<br>	`createTime` datetime ,<br>	`categoryName` varchar (600),<br>	`brandName` varchar (300),<br>	`spec` varchar (600)<br>); <br></code></pre></td></tr></table></figure>

<p>测试数据：测试数据：链接：<a target="_blank" rel="noopener" href="https://pan.baidu.com/s/14V3csJT1Xf2c-cKFDl7lNg">https://pan.baidu.com/s/14V3csJT1Xf2c-cKFDl7lNg</a><br>提取码：sxzx</p>
<p>添加文档数据</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs json">POST goods/_doc/<span class="hljs-number">1</span><br>&#123;<br>  <span class="hljs-attr">&quot;title&quot;</span>:<span class="hljs-string">&quot;小米手机&quot;</span>,<br>  <span class="hljs-attr">&quot;price&quot;</span>:<span class="hljs-number">1000</span>,<br>  <span class="hljs-attr">&quot;createTime&quot;</span>:<span class="hljs-string">&quot;2019-12-01&quot;</span>,<br>  <span class="hljs-attr">&quot;categoryName&quot;</span>:<span class="hljs-string">&quot;手机&quot;</span>,<br>  <span class="hljs-attr">&quot;brandName&quot;</span>:<span class="hljs-string">&quot;小米&quot;</span>,<br>  <span class="hljs-attr">&quot;saleNum&quot;</span>:<span class="hljs-number">3000</span>,<br>  <span class="hljs-attr">&quot;stock&quot;</span>:<span class="hljs-number">10000</span>,<br>  <span class="hljs-attr">&quot;spec&quot;</span>:&#123;<br>    <span class="hljs-attr">&quot;网络制式&quot;</span>:<span class="hljs-string">&quot;移动4G&quot;</span>,<br>    <span class="hljs-attr">&quot;屏幕尺寸&quot;</span>:<span class="hljs-string">&quot;4.5&quot;</span><br>  &#125;<br>&#125;<br><br># 查询文档数据<br>GET goods/_search<br></code></pre></td></tr></table></figure>

<p>添加坐标</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!--mybatis--&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.mybatis.spring.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>mybatis-spring-boot-starter<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.1.0<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>mysql<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>mysql-connector-java<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>添加 <code>application.yml</code> 配置文件</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs yml"><span class="hljs-comment"># datasource</span><br><span class="hljs-attr">spring:</span><br>  <span class="hljs-attr">datasource:</span><br>    <span class="hljs-attr">url:</span> <span class="hljs-string">jdbc:mysql:///es?serverTimezone=UTC</span><br>    <span class="hljs-attr">username:</span> <span class="hljs-string">root</span><br>    <span class="hljs-attr">password:</span> <span class="hljs-string">root</span><br>    <span class="hljs-attr">driver-class-name:</span> <span class="hljs-string">com.mysql.cj.jdbc.Driver</span><br><br><br><span class="hljs-comment"># mybatis</span><br><span class="hljs-attr">mybatis:</span><br>  <span class="hljs-attr">mapper-locations:</span> <span class="hljs-string">classpath:mapper/*Mapper.xml</span> <span class="hljs-comment"># mapper映射文件路径</span><br>  <span class="hljs-attr">type-aliases-package:</span> <span class="hljs-string">com.atguigu.domain</span><br></code></pre></td></tr></table></figure>

<p>添加 javabean</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Goods</span> </span>&#123;<br><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> id;<br>    <span class="hljs-keyword">private</span> String title;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">double</span> price;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> stock;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> saleNum;<br>    <span class="hljs-keyword">private</span> Date createTime;<br>    <span class="hljs-keyword">private</span> String categoryName;<br>    <span class="hljs-keyword">private</span> String brandName;<br>    <span class="hljs-keyword">private</span> Map spec;<br><br>   <span class="hljs-comment">// @JSONField(serialize = false)//在转换JSON时，忽略该字段</span><br>    <span class="hljs-keyword">private</span> String specStr;<span class="hljs-comment">//接收数据库的信息 &quot;&#123;&#125;&quot;</span><br>    <br>    <span class="hljs-comment">// 生成set  get  和 toString方法</span><br>    <br>&#125;    <br></code></pre></td></tr></table></figure>

<p>创建 dao</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Repository</span><br><span class="hljs-meta">@Mapper</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">GoodsMapper</span> </span>&#123;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 查询所有</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> List&lt;Goods&gt; <span class="hljs-title">findAll</span><span class="hljs-params">()</span></span>;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<p>​    在 <code>resource</code> 文件夹下面 创建 <code>mapper/GoodMapper.xml</code> 配置文件</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;</span><br><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">mapper</span> <span class="hljs-meta-keyword">PUBLIC</span> <span class="hljs-meta-string">&quot;-//mybatis.org//DTD Mapper 3.0//EN&quot;</span> <span class="hljs-meta-string">&quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">namespace</span>=<span class="hljs-string">&quot;com.atguigu.mapper.GoodsMapper&quot;</span>&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;findAll&quot;</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">&quot;goods&quot;</span>&gt;</span><br>        select<br>              `id`         ,<br>              `title`       ,<br>              `price`       ,<br>              `stock`       ,<br>              `saleNum`     ,<br>              `createTime`  ,<br>              `categoryName`,<br>              `brandName`   ,<br>              `spec`  as specStr<br>         from goods<br>    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span><br><br><br><span class="hljs-tag">&lt;/<span class="hljs-name">mapper</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>添加测试方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@SpringBootTest</span><br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ElasticsearchTest2</span> </span>&#123;<br><br>    <span class="hljs-meta">@Autowired</span><br>    <span class="hljs-keyword">private</span> GoodsMapper goodsMapper;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 批量导入</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">importData</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>        <span class="hljs-comment">//1.查询所有数据，mysql</span><br>        List&lt;Goods&gt; goodsList = goodsMapper.findAll();<br><br>        <span class="hljs-comment">//System.out.println(goodsList.size());</span><br>        <span class="hljs-comment">//2.bulk导入</span><br>        BulkRequest bulkRequest = <span class="hljs-keyword">new</span> BulkRequest();<br><br>        <span class="hljs-comment">//2.1 循环goodsList，创建IndexRequest添加数据</span><br>        <span class="hljs-keyword">for</span> (Goods goods : goodsList) &#123;<br>            <span class="hljs-comment">//2.2 设置spec规格信息 Map的数据   specStr:&#123;&#125;</span><br>            <span class="hljs-comment">//goods.setSpec(JSON.parseObject(goods.getSpecStr(),Map.class));</span><br><br>            String specStr = goods.getSpecStr();<br>            <span class="hljs-comment">//将json格式字符串转为Map集合</span><br>            Map map = JSON.parseObject(specStr, Map.class);<br>            <span class="hljs-comment">//设置spec map</span><br>            goods.setSpec(map);<br>            <span class="hljs-comment">//将goods对象转换为json字符串</span><br>            String data = JSON.toJSONString(goods);<span class="hljs-comment">//map --&gt; &#123;&#125;</span><br>            IndexRequest indexRequest = <span class="hljs-keyword">new</span> IndexRequest(<span class="hljs-string">&quot;goods&quot;</span>);<br>            indexRequest.id(goods.getId()+<span class="hljs-string">&quot;&quot;</span>).source(data, XContentType.JSON);<br>            bulkRequest.add(indexRequest);<br>        &#125;<br>        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);<br>        System.out.println(response.status());<br> &#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<p>查询数据是否导入</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs routeros"><span class="hljs-builtin-name">GET</span> goods/_search<br></code></pre></td></tr></table></figure>

<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s006.png" srcset="/img/loading.gif" lazyload></p>
<h3 id="查询所有matchAll查询"><a href="#查询所有matchAll查询" class="headerlink" title="查询所有matchAll查询"></a><a href="#%E6%9F%A5%E8%AF%A2%E6%89%80%E6%9C%89matchall%E6%9F%A5%E8%AF%A2">查询所有matchAll查询</a></h3><p>matchAll查询：查询所有文档</p>
<p><code>kibana</code> 演示</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"><br># 查询<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;match_all&quot;</span>: &#123;&#125;<br>  &#125;,<br>  <span class="hljs-attr">&quot;from&quot;</span>: <span class="hljs-number">0</span>,<br>  <span class="hljs-attr">&quot;size&quot;</span>: <span class="hljs-number">100</span><br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 查询所有</span><br><span class="hljs-comment">     *  1. matchAll</span><br><span class="hljs-comment">     *  2. 将查询结果封装为Goods对象，装载到List中</span><br><span class="hljs-comment">     *  3. 分页。默认显示10条</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMatchAll</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>        <span class="hljs-comment">//2. 构建查询请求对象，指定查询的索引名称</span><br>        SearchRequest searchRequest = <span class="hljs-keyword">new</span> SearchRequest(<span class="hljs-string">&quot;goods&quot;</span>);<br>        <span class="hljs-comment">//4. 创建查询条件构建器SearchSourceBuilder</span><br>        SearchSourceBuilder sourceBuilder = <span class="hljs-keyword">new</span> SearchSourceBuilder();<br><br>        <span class="hljs-comment">//6. 查询条件</span><br>        QueryBuilder query = QueryBuilders.matchAllQuery();<span class="hljs-comment">//查询所有文档</span><br>        <span class="hljs-comment">//5. 指定查询条件</span><br>        sourceBuilder.query(query);<br><br>        <span class="hljs-comment">//3. 添加查询条件构建器 SearchSourceBuilder</span><br>        searchRequest.source(sourceBuilder);<br><br>        <span class="hljs-comment">// 8 . 添加分页信息</span><br>        sourceBuilder.from(<span class="hljs-number">0</span>);<br>        sourceBuilder.size(<span class="hljs-number">100</span>);<br><br>        <span class="hljs-comment">//1. 查询,获取查询结果</span><br>        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);<br><br>        <span class="hljs-comment">//7. 获取命中对象 SearchHits</span><br>        SearchHits searchHits = searchResponse.getHits();<br>        <span class="hljs-comment">//7.1 获取总记录数</span><br>        <span class="hljs-keyword">long</span> value = searchHits.getTotalHits().value;<br>        System.out.println(<span class="hljs-string">&quot;总记录数：&quot;</span>+value);<br><br>        List&lt;Goods&gt; goodsList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        <span class="hljs-comment">//7.2 获取Hits数据  数组</span><br>        SearchHit[] hits = searchHits.getHits();<br>        <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>            <span class="hljs-comment">//获取json字符串格式的数据</span><br>            String sourceAsString = hit.getSourceAsString();<br>            <span class="hljs-comment">//转为java对象</span><br>            Goods goods = JSON.parseObject(sourceAsString, Goods.class);<br>            goodsList.add(goods);<br><br>        &#125;<br>        <span class="hljs-keyword">for</span> (Goods goods : goodsList) &#123;<br>            System.out.println(goods);<br>        &#125;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h3 id="term-查询"><a href="#term-查询" class="headerlink" title="term 查询"></a><a href="#term-%E6%9F%A5%E8%AF%A2">term 查询</a></h3><p>term查询：不会对查询条件进行分词。</p>
<p><code>kibana</code> 演示</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs json">GET goods<br><br># term 查询<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;term&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;categoryName&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;value&quot;</span>: <span class="hljs-string">&quot;手机&quot;</span><br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@SpringBootTest</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ElasticsearchTest2</span> </span>&#123;<br>   <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * termQuery:词条查询</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testTermQuery</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>        SearchRequest searchRequest = <span class="hljs-keyword">new</span> SearchRequest(<span class="hljs-string">&quot;goods&quot;</span>);<br>        SearchSourceBuilder sourceBulider = <span class="hljs-keyword">new</span> SearchSourceBuilder();<br><br>        QueryBuilder query = QueryBuilders.termQuery(<span class="hljs-string">&quot;title&quot;</span>,<span class="hljs-string">&quot;华为&quot;</span>);<span class="hljs-comment">//term词条查询</span><br>        sourceBulider.query(query);<br><br>        searchRequest.source(sourceBulider);<br>        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);<br><br>        SearchHits searchHits = searchResponse.getHits();<br>        <span class="hljs-comment">//获取记录数</span><br>        <span class="hljs-keyword">long</span> value = searchHits.getTotalHits().value;<br>        System.out.println(<span class="hljs-string">&quot;总记录数：&quot;</span>+value);<br><br>        List&lt;Goods&gt; goodsList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        SearchHit[] hits = searchHits.getHits();<br>        <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>            String sourceAsString = hit.getSourceAsString();<br><br>            <span class="hljs-comment">//转为java</span><br>            Goods goods = JSON.parseObject(sourceAsString, Goods.class);<br><br>            goodsList.add(goods);<br>        &#125;<br><br>        <span class="hljs-keyword">for</span> (Goods goods : goodsList) &#123;<br>            System.out.println(goods);<br>        &#125;<br>    &#125;<br> &#125;    <br></code></pre></td></tr></table></figure>

<h3 id="matchQuery-词条分词查询"><a href="#matchQuery-词条分词查询" class="headerlink" title="matchQuery:词条分词查询"></a>matchQuery:词条分词查询</h3><p>match查询：<br>• 会对查询条件进行分词。<br>• 然后将分词后的查询条件和词条进行等值匹配<br>• 默认取并集（OR）</p>
<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s007.png" srcset="/img/loading.gif" lazyload></p>
<p><code>kibana</code> 演示</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs json"># match 查询 <span class="hljs-string">&quot;title&quot;</span>: <span class="hljs-string">&quot;手机&quot;</span><br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;match&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;title&quot;</span>: <span class="hljs-string">&quot;华为&quot;</span><br>      <br>    &#125;<br>  &#125;<br>&#125;<br># match 查询  <span class="hljs-string">&quot;operator&quot;</span>: <span class="hljs-string">&quot;or&quot;</span><br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;match&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;title&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;query&quot;</span>: <span class="hljs-string">&quot;华为手机&quot;</span>,<br>        <span class="hljs-attr">&quot;operator&quot;</span>: <span class="hljs-string">&quot;and&quot;</span><br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * matchQuery:词条分词查询，分词之后的等值匹配</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testMatchQuery</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br><br><br>        SearchRequest searchRequest = <span class="hljs-keyword">new</span> SearchRequest(<span class="hljs-string">&quot;goods&quot;</span>);<br><br>        SearchSourceBuilder sourceBulider = <span class="hljs-keyword">new</span> SearchSourceBuilder();<br><br>        MatchQueryBuilder query = QueryBuilders.matchQuery(<span class="hljs-string">&quot;title&quot;</span>, <span class="hljs-string">&quot;华为手机&quot;</span>);<br>        query.operator(Operator.AND);<span class="hljs-comment">//求并集</span><br>        sourceBulider.query(query);<br><br>        searchRequest.source(sourceBulider);<br><br><br>        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);<br><br><br>        SearchHits searchHits = searchResponse.getHits();<br>        <span class="hljs-comment">//获取记录数</span><br>        <span class="hljs-keyword">long</span> value = searchHits.getTotalHits().value;<br>        System.out.println(<span class="hljs-string">&quot;总记录数：&quot;</span>+value);<br><br>        List&lt;Goods&gt; goodsList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        SearchHit[] hits = searchHits.getHits();<br>        <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>            String sourceAsString = hit.getSourceAsString();<br><br>            <span class="hljs-comment">//转为java</span><br>            Goods goods = JSON.parseObject(sourceAsString, Goods.class);<br><br>            goodsList.add(goods);<br>        &#125;<br><br>        <span class="hljs-keyword">for</span> (Goods goods : goodsList) &#123;<br>            System.out.println(goods);<br>        &#125;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h3 id="模糊查询-脚本"><a href="#模糊查询-脚本" class="headerlink" title="模糊查询-脚本"></a>模糊查询-脚本</h3><p>wildcard查询：会对查询条件进行分词。还可以使用通配符 ?（任意单个字符） 和 * （0个或多个字符）<br>prefix查询：前缀查询</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs json"># wildcard 查询。查询条件分词，模糊查询 华为，华，*华*<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;wildcard&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;title&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;value&quot;</span>: <span class="hljs-string">&quot;华*&quot;</span> <br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;<br><br><br># 前缀查询<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;prefix&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;brandName&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;value&quot;</span>: <span class="hljs-string">&quot;三&quot;</span><br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 模糊查询:WildcardQuery</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testWildcardQuery</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br><br><br>        SearchRequest searchRequest = <span class="hljs-keyword">new</span> SearchRequest(<span class="hljs-string">&quot;goods&quot;</span>);<br><br>        SearchSourceBuilder sourceBulider = <span class="hljs-keyword">new</span> SearchSourceBuilder();<br><br>        WildcardQueryBuilder query = QueryBuilders.wildcardQuery(<span class="hljs-string">&quot;title&quot;</span>, <span class="hljs-string">&quot;华*&quot;</span>);<br><br>        sourceBulider.query(query);<br><br>        searchRequest.source(sourceBulider);<br><br><br>        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);<br><br><br>        SearchHits searchHits = searchResponse.getHits();<br>        <span class="hljs-comment">//获取记录数</span><br>        <span class="hljs-keyword">long</span> value = searchHits.getTotalHits().value;<br>        System.out.println(<span class="hljs-string">&quot;总记录数：&quot;</span>+value);<br><br>        List&lt;Goods&gt; goodsList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        SearchHit[] hits = searchHits.getHits();<br>        <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>            String sourceAsString = hit.getSourceAsString();<br><br>            <span class="hljs-comment">//转为java</span><br>            Goods goods = JSON.parseObject(sourceAsString, Goods.class);<br><br>            goodsList.add(goods);<br>        &#125;<br>        <span class="hljs-keyword">for</span> (Goods goods : goodsList) &#123;<br>            System.out.println(goods);<br>        &#125;<br>    &#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 模糊查询:perfixQuery</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testPrefixQuery</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br><br><br>        SearchRequest searchRequest = <span class="hljs-keyword">new</span> SearchRequest(<span class="hljs-string">&quot;goods&quot;</span>);<br><br>        SearchSourceBuilder sourceBulider = <span class="hljs-keyword">new</span> SearchSourceBuilder();<br><br>        PrefixQueryBuilder query = QueryBuilders.prefixQuery(<span class="hljs-string">&quot;brandName&quot;</span>, <span class="hljs-string">&quot;三&quot;</span>);<br><br>        sourceBulider.query(query);<br><br>        searchRequest.source(sourceBulider);<br><br><br>        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);<br><br><br>        SearchHits searchHits = searchResponse.getHits();<br>        <span class="hljs-comment">//获取记录数</span><br>        <span class="hljs-keyword">long</span> value = searchHits.getTotalHits().value;<br>        System.out.println(<span class="hljs-string">&quot;总记录数：&quot;</span>+value);<br><br>        List&lt;Goods&gt; goodsList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        SearchHit[] hits = searchHits.getHits();<br>        <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>            String sourceAsString = hit.getSourceAsString();<br><br>            <span class="hljs-comment">//转为java</span><br>            Goods goods = JSON.parseObject(sourceAsString, Goods.class);<br><br>            goodsList.add(goods);<br>        &#125;<br><br>        <span class="hljs-keyword">for</span> (Goods goods : goodsList) &#123;<br>            System.out.println(goods);<br>        &#125;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h3 id="范围查询-脚本"><a href="#范围查询-脚本" class="headerlink" title="范围查询-脚本"></a>范围查询-脚本</h3><p>range 范围查询：查找指定字段在指定范围内包含值</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs json"># 范围查询 gte 大于等于 lte小于等于<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;range&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;price&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;gte&quot;</span>: <span class="hljs-number">2000</span>,<br>        <span class="hljs-attr">&quot;lte&quot;</span>: <span class="hljs-number">3000</span><br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;<br><br># 范围查询 gte 大于等于 lte小于等于<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;range&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;price&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;gte&quot;</span>: <span class="hljs-number">2000</span>,<br>        <span class="hljs-attr">&quot;lte&quot;</span>: <span class="hljs-number">3000</span><br>      &#125;<br>    &#125;<br>  &#125;,<br>  <span class="hljs-attr">&quot;sort&quot;</span>: [<br>    &#123;<br>      <span class="hljs-attr">&quot;price&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;order&quot;</span>: <span class="hljs-string">&quot;desc&quot;</span><br>      &#125;<br>    &#125;<br>  ]<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 1. 范围查询：rangeQuery</span><br><span class="hljs-comment">     * 2. 排序</span><br><span class="hljs-comment">     */</span><br>    @Test<br>    public void testRangeQuery() throws IOException &#123;<br>        SearchRequest searchRequest = new SearchRequest(<span class="hljs-attr">&quot;goods&quot;</span>);<br><br>        SearchSourceBuilder sourceBulider = new SearchSourceBuilder();<br><br>        <span class="hljs-comment">//范围查询</span><br>        RangeQueryBuilder query = QueryBuilders.rangeQuery(<span class="hljs-attr">&quot;price&quot;</span>);<br><br>        <span class="hljs-comment">//指定下限 gte大于等于</span><br>        query.gte(2000);<br>        <span class="hljs-comment">//指定上限 小于等于</span><br>        query.lte(3000);<br><br>        sourceBulider.query(query);<br><br>        <span class="hljs-comment">//排序</span><br>        sourceBulider.sort(<span class="hljs-attr">&quot;price&quot;</span>, SortOrder.DESC);<br>        searchRequest.source(sourceBulider);<br><br>        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);<br>        SearchHits searchHits = searchResponse.getHits();<br>        <span class="hljs-comment">//获取记录数</span><br>        long value = searchHits.getTotalHits().value;<br>        System.out.println(<span class="hljs-attr">&quot;总记录数：&quot;</span>+value);<br><br>        List&lt;Goods&gt; goodsList = new ArrayList&lt;&gt;();<br>        SearchHit[] hits = searchHits.getHits();<br>        for (SearchHit hit : hits) &#123;<br>            String sourceAsString = hit.getSourceAsString();<br><br>            <span class="hljs-comment">//转为java</span><br>            Goods goods = JSON.parseObject(sourceAsString, Goods.class);<br><br>            goodsList.add(goods);<br>        &#125;<br>        for (Goods goods : goodsList) &#123;<br>            System.out.println(goods);<br>        &#125;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h3 id="queryString查询-脚本"><a href="#queryString查询-脚本" class="headerlink" title="queryString查询-脚本"></a>queryString查询-脚本</h3><p>queryString：<br>• 会对查询条件进行分词。<br>• 然后将分词后的查询条件和词条进行等值匹配<br>• 默认取并集（OR）<br>• 可以指定多个查询字段</p>
<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s008.png" srcset="/img/loading.gif" lazyload></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs json"># queryString<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;query_string&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;fields&quot;</span>: [<span class="hljs-string">&quot;title&quot;</span>,<span class="hljs-string">&quot;categoryName&quot;</span>,<span class="hljs-string">&quot;brandName&quot;</span>],<br>      <span class="hljs-attr">&quot;query&quot;</span>: <span class="hljs-string">&quot;华为&quot;</span><br>    &#125;<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * queryString</span><br><span class="hljs-comment">     */</span><br>    @Test<br>    public void testQueryStringQuery() throws IOException &#123;<br><br><br>        SearchRequest searchRequest = new SearchRequest(<span class="hljs-attr">&quot;goods&quot;</span>);<br><br>        SearchSourceBuilder sourceBulider = new SearchSourceBuilder();<br><br>        <span class="hljs-comment">//queryString</span><br>        QueryStringQueryBuilder query = QueryBuilders.queryStringQuery(<span class="hljs-attr">&quot;华为手机&quot;</span>)<br>                .field(<span class="hljs-attr">&quot;title&quot;</span>)<br>                .field(<span class="hljs-attr">&quot;categoryName&quot;</span>)<br>                .field(<span class="hljs-attr">&quot;brandName&quot;</span>)<br>                .defaultOperator(Operator.AND);<br>        sourceBulider.query(query);<br>        searchRequest.source(sourceBulider);<br><br>        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);<br>        SearchHits searchHits = searchResponse.getHits();<br>        <span class="hljs-comment">//获取记录数</span><br>        long value = searchHits.getTotalHits().value;<br>        System.out.println(<span class="hljs-attr">&quot;总记录数：&quot;</span>+value);<br><br>        List&lt;Goods&gt; goodsList = new ArrayList&lt;&gt;();<br>        SearchHit[] hits = searchHits.getHits();<br>        for (SearchHit hit : hits) &#123;<br>            String sourceAsString = hit.getSourceAsString();<br><br>            <span class="hljs-comment">//转为java</span><br>            Goods goods = JSON.parseObject(sourceAsString, Goods.class);<br><br>            goodsList.add(goods);<br>        &#125;<br><br>        for (Goods goods : goodsList) &#123;<br>            System.out.println(goods);<br>        &#125;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h3 id="布尔查询"><a href="#布尔查询" class="headerlink" title="布尔查询"></a><a href="#%E5%B8%83%E5%B0%94%E6%9F%A5%E8%AF%A2">布尔查询</a></h3><p>boolQuery：对多个查询条件连接。连接方式：<br>• must（and）：条件必须成立<br>• must_not（not）：条件必须不成立<br>• should（or）：条件可以成立<br>• filter：条件必须成立，性能比must高。不会计算得分</p>
<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s009.png" srcset="/img/loading.gif" lazyload></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs json">GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;match&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;title&quot;</span>: <span class="hljs-string">&quot;华为手机&quot;</span><br>    &#125;<br>  &#125;,<br>  <span class="hljs-attr">&quot;size&quot;</span>: <span class="hljs-number">500</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s010.png" srcset="/img/loading.gif" lazyload></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><code class="hljs json"># 计算得分<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;bool&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;must&quot;</span>: [<br>        &#123;<br>          <span class="hljs-attr">&quot;term&quot;</span>: &#123;<br>            <span class="hljs-attr">&quot;brandName&quot;</span>: &#123;<br>              <span class="hljs-attr">&quot;value&quot;</span>: <span class="hljs-string">&quot;华为&quot;</span><br>            &#125;<br>          &#125;<br>        &#125;<br>      ]<br>    &#125;<br>  &#125;<br>&#125;<br><br># 不计算得分<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;bool&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;filter&quot;</span>: [<br>        &#123;<br>          <span class="hljs-attr">&quot;term&quot;</span>: &#123;<br>            <span class="hljs-attr">&quot;brandName&quot;</span>: &#123;<br>              <span class="hljs-attr">&quot;value&quot;</span>: <span class="hljs-string">&quot;华为&quot;</span><br>            &#125;<br>          &#125;<br>        &#125;  <br>      ]<br>    &#125;<br>  &#125;<br>&#125;<br><br><br># 计算得分 品牌是三星，标题还得电视<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;bool&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;must&quot;</span>: [<br>        &#123;<br>          <span class="hljs-attr">&quot;term&quot;</span>: &#123;<br>            <span class="hljs-attr">&quot;brandName&quot;</span>: &#123;<br>              <span class="hljs-attr">&quot;value&quot;</span>: <span class="hljs-string">&quot;三星&quot;</span><br>            &#125;<br>          &#125;<br>        &#125;<br>      ],<br>      <span class="hljs-attr">&quot;filter&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;term&quot;</span>: &#123;<br>          <span class="hljs-attr">&quot;title&quot;</span>: <span class="hljs-string">&quot;电视&quot;</span><br>        &#125;<br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 布尔查询：boolQuery</span><br><span class="hljs-comment">     * 1. 查询品牌名称为:华为</span><br><span class="hljs-comment">     * 2. 查询标题包含：手机</span><br><span class="hljs-comment">     * 3. 查询价格在：2000-3000</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testBoolQuery</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br><br>        SearchRequest searchRequest = <span class="hljs-keyword">new</span> SearchRequest(<span class="hljs-string">&quot;goods&quot;</span>);<br>        SearchSourceBuilder sourceBulider = <span class="hljs-keyword">new</span> SearchSourceBuilder();<br>        <span class="hljs-comment">//1.构建boolQuery</span><br>        BoolQueryBuilder query = QueryBuilders.boolQuery();<br><br>        <span class="hljs-comment">//2.构建各个查询条件</span><br>        <span class="hljs-comment">//2.1 查询品牌名称为:华为</span><br>        QueryBuilder termQuery = QueryBuilders.termQuery(<span class="hljs-string">&quot;brandName&quot;</span>,<span class="hljs-string">&quot;华为&quot;</span>);<br>        query.must(termQuery);<br><br>        <span class="hljs-comment">//2.2. 查询标题包含：手机</span><br>        QueryBuilder matchQuery = QueryBuilders.matchQuery(<span class="hljs-string">&quot;title&quot;</span>,<span class="hljs-string">&quot;手机&quot;</span>);<br>        query.filter(matchQuery);<br><br>        <span class="hljs-comment">//2.3 查询价格在：2000-3000</span><br>        QueryBuilder rangeQuery = QueryBuilders.rangeQuery(<span class="hljs-string">&quot;price&quot;</span>);<br>        ((RangeQueryBuilder) rangeQuery).gte(<span class="hljs-number">2000</span>);<br>        ((RangeQueryBuilder) rangeQuery).lte(<span class="hljs-number">3000</span>);<br>        query.filter(rangeQuery);<br><br>        <span class="hljs-comment">//3.使用boolQuery连接</span><br>        sourceBulider.query(query);<br>        searchRequest.source(sourceBulider);<br><br>        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);<br><br><br>        SearchHits searchHits = searchResponse.getHits();<br>        <span class="hljs-comment">//获取记录数</span><br>        <span class="hljs-keyword">long</span> value = searchHits.getTotalHits().value;<br>        System.out.println(<span class="hljs-string">&quot;总记录数：&quot;</span>+value);<br><br>        List&lt;Goods&gt; goodsList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        SearchHit[] hits = searchHits.getHits();<br>        <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>            String sourceAsString = hit.getSourceAsString();<br><br>            <span class="hljs-comment">//转为java</span><br>            Goods goods = JSON.parseObject(sourceAsString, Goods.class);<br><br>            goodsList.add(goods);<br>        &#125;<br><br>        <span class="hljs-keyword">for</span> (Goods goods : goodsList) &#123;<br>            System.out.println(goods);<br>        &#125;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h3 id="聚合查询"><a href="#聚合查询" class="headerlink" title="聚合查询"></a><a href="#%E8%81%9A%E5%90%88%E6%9F%A5%E8%AF%A2">聚合查询</a></h3><p>• 指标聚合：相当于MySQL的聚合函数。max、min、avg、sum等<br>• 桶聚合：相当于MySQL的 group by 操作。不要对text类型的数据进行分组，会失败。</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs json"># 查询最贵的华为手机，max_price命名随便取，取一个有意义的名字<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;match&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;title&quot;</span>: <span class="hljs-string">&quot;华为手机&quot;</span><br>    &#125;<br>  &#125;,<br>  <span class="hljs-attr">&quot;aggs&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;max_price&quot;</span>:&#123;<br>      <span class="hljs-attr">&quot;max&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;field&quot;</span>: <span class="hljs-string">&quot;price&quot;</span><br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;<br><br># 桶聚合 分组<br>GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;match&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;title&quot;</span>: <span class="hljs-string">&quot;电视&quot;</span><br>    &#125;<br>  &#125;,<br>  <span class="hljs-attr">&quot;aggs&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;goods_brands&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;terms&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;field&quot;</span>: <span class="hljs-string">&quot;brandName&quot;</span>,<br>        <span class="hljs-attr">&quot;size&quot;</span>: <span class="hljs-number">100</span><br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 聚合查询：桶聚合，分组查询</span><br><span class="hljs-comment">     * 1. 查询title包含手机的数据</span><br><span class="hljs-comment">     * 2. 查询品牌列表</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testAggQuery</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br><br>        SearchRequest searchRequest = <span class="hljs-keyword">new</span> SearchRequest(<span class="hljs-string">&quot;goods&quot;</span>);<br><br>        SearchSourceBuilder sourceBulider = <span class="hljs-keyword">new</span> SearchSourceBuilder();<br><br>        <span class="hljs-comment">// 1. 查询title包含手机的数据</span><br>        MatchQueryBuilder query = QueryBuilders.matchQuery(<span class="hljs-string">&quot;title&quot;</span>, <span class="hljs-string">&quot;手机&quot;</span>);<br><br>        sourceBulider.query(query);<br><br>        <span class="hljs-comment">// 2. 查询品牌列表</span><br>        <span class="hljs-comment">/*</span><br><span class="hljs-comment">        参数：</span><br><span class="hljs-comment">            1. 自定义的名称，将来用于获取数据</span><br><span class="hljs-comment">            2. 分组的字段</span><br><span class="hljs-comment">         */</span><br>        AggregationBuilder agg = AggregationBuilders.terms(<span class="hljs-string">&quot;goods_brands&quot;</span>).field(<span class="hljs-string">&quot;brandName&quot;</span>).size(<span class="hljs-number">100</span>);<br>        sourceBulider.aggregation(agg);<br><br>        searchRequest.source(sourceBulider);<br>        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);<br><br>        SearchHits searchHits = searchResponse.getHits();<br>        <span class="hljs-comment">//获取记录数</span><br>        <span class="hljs-keyword">long</span> value = searchHits.getTotalHits().value;<br>        System.out.println(<span class="hljs-string">&quot;总记录数：&quot;</span>+value);<br><br>        List&lt;Goods&gt; goodsList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        SearchHit[] hits = searchHits.getHits();<br>        <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>            String sourceAsString = hit.getSourceAsString();<br><br>            <span class="hljs-comment">//转为java</span><br>            Goods goods = JSON.parseObject(sourceAsString, Goods.class);<br><br>            goodsList.add(goods);<br>        &#125;<br><br>        <span class="hljs-keyword">for</span> (Goods goods : goodsList) &#123;<br>            System.out.println(goods);<br>        &#125;<br><br>        <span class="hljs-comment">// 获取聚合结果</span><br>        Aggregations aggregations = searchResponse.getAggregations();<br><br>        Map&lt;String, Aggregation&gt; aggregationMap = aggregations.asMap();<br><br>        <span class="hljs-comment">//System.out.println(aggregationMap);</span><br>        Terms goods_brands = (Terms) aggregationMap.get(<span class="hljs-string">&quot;goods_brands&quot;</span>);<br><br>        List&lt;? extends Terms.Bucket&gt; buckets = goods_brands.getBuckets();<br><br>        List brands = <span class="hljs-keyword">new</span> ArrayList();<br>        <span class="hljs-keyword">for</span> (Terms.Bucket bucket : buckets) &#123;<br>            Object key = bucket.getKey();<br>            brands.add(key);<br>        &#125;<br><br>        <span class="hljs-keyword">for</span> (Object brand : brands) &#123;<br>            System.out.println(brand);<br>        &#125;<br>    &#125;<br></code></pre></td></tr></table></figure>

<h3 id="高亮查询"><a href="#高亮查询" class="headerlink" title="高亮查询"></a><a href="#%E9%AB%98%E4%BA%AE%E6%9F%A5%E8%AF%A2">高亮查询</a></h3><p>高亮三要素：<br>• 高亮字段<br>• 前缀<br>• 后缀</p>
<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s011.png" srcset="/img/loading.gif" lazyload></p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs json">GET goods/_search<br>&#123;<br>  <span class="hljs-attr">&quot;query&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;match&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;title&quot;</span>: <span class="hljs-string">&quot;电视&quot;</span><br>    &#125;<br>  &#125;,<br>  <span class="hljs-attr">&quot;highlight&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;fields&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;title&quot;</span>: &#123;<br>        <span class="hljs-attr">&quot;pre_tags&quot;</span>: <span class="hljs-string">&quot;&lt;font color=&#x27;red&#x27;&gt;&quot;</span>,<br>        <span class="hljs-attr">&quot;post_tags&quot;</span>: <span class="hljs-string">&quot;&lt;/font&gt;&quot;</span><br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    *</span><br><span class="hljs-comment">    * 高亮查询：</span><br><span class="hljs-comment">    *  1. 设置高亮</span><br><span class="hljs-comment">    *      * 高亮字段</span><br><span class="hljs-comment">    *      * 前缀</span><br><span class="hljs-comment">    *      * 后缀</span><br><span class="hljs-comment">    *  2. 将高亮了的字段数据，替换原有数据</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-meta">@Test</span><br>   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testHighLightQuery</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;<br>       SearchRequest searchRequest = <span class="hljs-keyword">new</span> SearchRequest(<span class="hljs-string">&quot;goods&quot;</span>);<br><br>       SearchSourceBuilder sourceBulider = <span class="hljs-keyword">new</span> SearchSourceBuilder();<br><br>       <span class="hljs-comment">// 1. 查询title包含手机的数据</span><br>       MatchQueryBuilder query = QueryBuilders.matchQuery(<span class="hljs-string">&quot;title&quot;</span>, <span class="hljs-string">&quot;手机&quot;</span>);<br><br>       sourceBulider.query(query);<br><br>       <span class="hljs-comment">//设置高亮</span><br>       HighlightBuilder highlighter = <span class="hljs-keyword">new</span> HighlightBuilder();<br>       <span class="hljs-comment">//设置三要素</span><br>       highlighter.field(<span class="hljs-string">&quot;title&quot;</span>);<br>       highlighter.preTags(<span class="hljs-string">&quot;&lt;font color=&#x27;red&#x27;&gt;&quot;</span>);<br>       highlighter.postTags(<span class="hljs-string">&quot;&lt;/font&gt;&quot;</span>);<br>       sourceBulider.highlighter(highlighter);<br>       <span class="hljs-comment">// 2. 查询品牌列表</span><br>       <span class="hljs-comment">/*</span><br><span class="hljs-comment">       参数：</span><br><span class="hljs-comment">           1. 自定义的名称，将来用于获取数据</span><br><span class="hljs-comment">           2. 分组的字段</span><br><span class="hljs-comment">        */</span><br>       AggregationBuilder agg = AggregationBuilders.terms(<span class="hljs-string">&quot;goods_brands&quot;</span>).field(<span class="hljs-string">&quot;brandName&quot;</span>).size(<span class="hljs-number">100</span>);<br>       sourceBulider.aggregation(agg);<br><br>       searchRequest.source(sourceBulider);<br>       SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);<br><br>       SearchHits searchHits = searchResponse.getHits();<br>       <span class="hljs-comment">//获取记录数</span><br>       <span class="hljs-keyword">long</span> value = searchHits.getTotalHits().value;<br>       System.out.println(<span class="hljs-string">&quot;总记录数：&quot;</span>+value);<br><br>       List&lt;Goods&gt; goodsList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>       SearchHit[] hits = searchHits.getHits();<br>       <span class="hljs-keyword">for</span> (SearchHit hit : hits) &#123;<br>           String sourceAsString = hit.getSourceAsString();<br><br>           <span class="hljs-comment">//转为java</span><br>           Goods goods = JSON.parseObject(sourceAsString, Goods.class);<br><br>           <span class="hljs-comment">// 获取高亮结果，替换goods中的title</span><br>           Map&lt;String, HighlightField&gt; highlightFields = hit.getHighlightFields();<br>           HighlightField HighlightField = highlightFields.get(<span class="hljs-string">&quot;title&quot;</span>);<br>           Text[] fragments = HighlightField.fragments();<br>           <span class="hljs-comment">//替换</span><br>           goods.setTitle(fragments[<span class="hljs-number">0</span>].toString());<br><br><br>           goodsList.add(goods);<br>       &#125;<br><br>       <span class="hljs-keyword">for</span> (Goods goods : goodsList) &#123;<br>           System.out.println(goods);<br>       &#125;<br><br>   &#125;<br></code></pre></td></tr></table></figure>

<h3 id="重建索引"><a href="#重建索引" class="headerlink" title="重建索引"></a><a href="#%E9%87%8D%E5%BB%BA%E7%B4%A2%E5%BC%95">重建索引</a></h3><p>随着业务需求的变更，索引的结构可能发生改变。<br>ElasticSearch的索引一旦创建，只允许添加字段，不允许改变字段。因为改变字段，需要重建倒排索引，影响内部缓<br>存结构，性能太低。<br>那么此时，就需要重建一个新的索引，并将原有索引的数据导入到新索引中。</p>
<p>原索引库 ：student_index_v1</p>
<p>新索引库 ：student_index_v2</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><code class="hljs json"># 新建student_index_v1索引，索引名称必须全部小写<br>PUT student_index_v1 <br>&#123;<br>  <span class="hljs-attr">&quot;mappings&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;properties&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;birthday&quot;</span>:&#123;<br>        <span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;date&quot;</span><br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;<br># 查询索引<br>GET student_index_v1<br># 添加数据<br>PUT student_index_v1/_doc/<span class="hljs-number">1</span><br>&#123;<br>  <span class="hljs-attr">&quot;birthday&quot;</span>:<span class="hljs-string">&quot;2020-11-11&quot;</span><br>&#125;<br># 查询数据<br>GET student_index_v1/_search<br># 随着业务的变更，换种数据类型进行添加数据，程序会直接报错<br>PUT student_index_v1/_doc/<span class="hljs-number">1</span><br>&#123;<br>  <span class="hljs-attr">&quot;birthday&quot;</span>:<span class="hljs-string">&quot;2020年11月11号&quot;</span><br>&#125;<br># 业务变更，需要改变birthday数据类型为text<br># <span class="hljs-number">1</span>：创建新的索引 student_index_v2<br># <span class="hljs-number">2</span>：将student_index_v1 数据拷贝到 student_index_v2<br><br># 创建新的索引<br>PUT student_index_v2 <br>&#123;<br>  <span class="hljs-attr">&quot;mappings&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;properties&quot;</span>: &#123;<br>      <span class="hljs-attr">&quot;birthday&quot;</span>:&#123;<br>        <span class="hljs-attr">&quot;type&quot;</span>: <span class="hljs-string">&quot;text&quot;</span><br>      &#125;<br>    &#125;<br>  &#125;<br>&#125;<br><br>DELETE student_index_v2<br># <span class="hljs-number">2</span>：将student_index_v1 数据拷贝到 student_index_v2<br>POST _reindex<br>&#123;<br>  <span class="hljs-attr">&quot;source&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;index&quot;</span>: <span class="hljs-string">&quot;student_index_v1&quot;</span><br>  &#125;,<br>  <span class="hljs-attr">&quot;dest&quot;</span>: &#123;<br>    <span class="hljs-attr">&quot;index&quot;</span>: <span class="hljs-string">&quot;student_index_v2&quot;</span><br>  &#125;<br>&#125;<br># 查询新索引库数据<br>GET student_index_v2/_search<br># 在新的索引库里面添加数据<br>PUT student_index_v2/_doc/<span class="hljs-number">2</span><br>&#123;<br>  <span class="hljs-attr">&quot;birthday&quot;</span>:<span class="hljs-string">&quot;2020年11月13号&quot;</span><br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="2-SpringData-Elasticsearch客户端"><a href="#2-SpringData-Elasticsearch客户端" class="headerlink" title="2 SpringData Elasticsearch客户端"></a><a href="#2-springdata-elasticsearch%E5%AE%A2%E6%88%B7%E7%AB%AF">2 SpringData Elasticsearch客户端</a></h2><h3 id="目标"><a href="#目标" class="headerlink" title="目标"></a>目标</h3><ul>
<li>SpringData的作用:简化了数据库的增删改查操作</li>
<li>SpringDataElasticsearch入门[掌握]</li>
<li>SpringDataElasticsearch查询命名规则[掌握]</li>
</ul>
<h4 id="SpringDataJpa介绍-集成"><a href="#SpringDataJpa介绍-集成" class="headerlink" title="SpringDataJpa介绍[集成]"></a>SpringDataJpa介绍[集成]</h4><p>JPA是一个规范，真正操作数据库的是Hibernate（实现数据库增删改查框架[ORM框架],操作数据库采用的方式是面向对象[不写SQL语句]），而springdatajpa是对jpa的封装，将CRUD的方法封装到指定的方法中，操作的时候，只需要调用方法即可。</p>
<p>Spring Data Jpa的实现过程：</p>
<ol>
<li>定义实体，实体类添加Jpa的注解  @Entity  @Talbe @Cloumn @Id</li>
<li>定义接口，接口要继承JpaRepository的接口</li>
<li>配置spring容器，applicationContext.xml/SpringApplication.run(T.class,args)</li>
</ol>
<h4 id="Spring-Data-ElasticSearch简介"><a href="#Spring-Data-ElasticSearch简介" class="headerlink" title="Spring Data ElasticSearch简介"></a>Spring Data ElasticSearch简介</h4><p>(1)SpringData介绍</p>
<p>Spring Data是一个用于简化数据库、非关系型数据库、索引库访问，并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷，并支持map-reduce框架和云计算数据服务。 Spring Data可以极大的简化JPA（Elasticsearch…）的写法，可以在几乎不用写实现的情况下，实现对数据的访问和操作。除了CRUD外，还包括如分页、排序等一些常用的功能。</p>
<p>Spring Data的官网：<a target="_blank" rel="noopener" href="http://projects.spring.io/spring-data/">http://projects.spring.io/spring-data/</a></p>
<p>Spring Data常用的功能模块如下：</p>
<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s012.png" srcset="/img/loading.gif" lazyload></p>
<p><img src="http://www.slx.blue/2022/01/11/ElasticSearch/s013.png" srcset="/img/loading.gif" lazyload></p>
<p>(2)SpringData Elasticsearch介绍</p>
<p>Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作，将原始操作elasticSearch的客户端API 进行封装 。Spring Data为Elasticsearch项目提供集成搜索引擎。Spring Data Elasticsearch POJO的关键功能区域为中心的模型与Elastichsearch交互文档和轻松地编写一个存储索引库数据访问层。</p>
<p>官方网站：<a target="_blank" rel="noopener" href="http://projects.spring.io/spring-data-elasticsearch/">http://projects.spring.io/spring-data-elasticsearch/</a></p>
<h4 id="SpringData-Elasticsearch入门"><a href="#SpringData-Elasticsearch入门" class="headerlink" title="SpringData Elasticsearch入门"></a>SpringData Elasticsearch入门</h4><h5 id="搭建工程"><a href="#搭建工程" class="headerlink" title="搭建工程"></a>搭建工程</h5><p>(1)搭建工程</p>
<p>创建项目 <code>elasticsearch-springdata-es</code></p>
<p>(2)pom.xml依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">project</span> <span class="hljs-attr">xmlns</span>=<span class="hljs-string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span></span><br><span class="hljs-tag">         <span class="hljs-attr">xmlns:xsi</span>=<span class="hljs-string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span><br><span class="hljs-tag">         <span class="hljs-attr">xsi:schemaLocation</span>=<span class="hljs-string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">modelVersion</span>&gt;</span>4.0.0<span class="hljs-tag">&lt;/<span class="hljs-name">modelVersion</span>&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.atguigu<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>elasticsearch-springdata-es<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.0-SNAPSHOT<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br><br>     <span class="hljs-tag">&lt;<span class="hljs-name">parent</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.2.1.RELEASE<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">parent</span>&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-data-elasticsearch<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>junit<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>4.12<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">scope</span>&gt;</span>test<span class="hljs-tag">&lt;/<span class="hljs-name">scope</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span><br><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">build</span>&gt;</span><br>        <span class="hljs-tag">&lt;<span class="hljs-name">plugins</span>&gt;</span><br>            <span class="hljs-comment">&lt;!-- java编译插件 --&gt;</span><br>            <span class="hljs-tag">&lt;<span class="hljs-name">plugin</span>&gt;</span><br>                <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.apache.maven.plugins<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>                <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>maven-compiler-plugin<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br>                <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>3.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span><br>                <span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span><br>                    <span class="hljs-tag">&lt;<span class="hljs-name">source</span>&gt;</span>1.8<span class="hljs-tag">&lt;/<span class="hljs-name">source</span>&gt;</span><br>                    <span class="hljs-tag">&lt;<span class="hljs-name">target</span>&gt;</span>1.8<span class="hljs-tag">&lt;/<span class="hljs-name">target</span>&gt;</span><br>                    <span class="hljs-tag">&lt;<span class="hljs-name">encoding</span>&gt;</span>UTF-8<span class="hljs-tag">&lt;/<span class="hljs-name">encoding</span>&gt;</span><br>                <span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span><br>            <span class="hljs-tag">&lt;/<span class="hljs-name">plugin</span>&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">plugins</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">build</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">project</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h5 id="增加索引数据"><a href="#增加索引数据" class="headerlink" title="增加索引数据"></a>增加索引数据</h5><p>(1)编写实体类</p>
<p>创建<code>com.atguigu.domain.Item</code>，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Data</span><br><span class="hljs-meta">@AllArgsConstructor</span><br><span class="hljs-meta">@NoArgsConstructor</span><br><span class="hljs-meta">@ToString</span><br><span class="hljs-meta">@Document(indexName = &quot;item&quot;,shards = 1,replicas = 1)</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Item</span> </span>&#123;<br>    <span class="hljs-meta">@Id</span><br>    <span class="hljs-keyword">private</span> Long id;<br><br>    <span class="hljs-meta">@Field(type = FieldType.Text,analyzer = &quot;ik_max_word&quot;)</span><br>    <span class="hljs-keyword">private</span> String title;<br><br>    <span class="hljs-meta">@Field(type = FieldType.Keyword)</span><br>    <span class="hljs-keyword">private</span> String category;<span class="hljs-comment">// 分类</span><br><br>    <span class="hljs-meta">@Field(type = FieldType.Keyword)</span><br>    <span class="hljs-keyword">private</span> String brand; <span class="hljs-comment">// 品牌</span><br><br>    <span class="hljs-meta">@Field(type = FieldType.Double)</span><br>    <span class="hljs-keyword">private</span> Double price; <span class="hljs-comment">// 价格</span><br><br>    <span class="hljs-meta">@Field(index = false, type = FieldType.Keyword)</span><br>    <span class="hljs-keyword">private</span> String images; <span class="hljs-comment">// 图片地址</span><br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>映射</p>
</blockquote>
<p>Spring Data通过注解来声明字段的映射属性，有下面的三个注解：</p>
<p>@Document 作用在类，标记实体类为文档对象，一般有四个属性<br>indexName：对应索引库名称<br>shards：分片数量，默认5<br>replicas：副本数量，默认1<br>@Id 作用在成员变量，标记一个字段作为id主键<br>@Field 作用在成员变量，标记为文档的字段，并指定字段映射属性：<br>type：字段类型，取值是枚举：FieldType<br>index：是否索引，布尔类型，默认是true<br>store：是否存储，布尔类型，默认是false<br>analyzer：分词器名称：ik_max_word</p>
<p>配置 <code>application.yml</code> 文件</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs xml-dtd">spring:<br>  data:<br>    elasticsearch:<br>      cluster-name: elasticsearch   #自己ES中配置文件的cluster-name<br>      cluster-nodes: 127.0.0.1:9300<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RunWith(SpringRunner.class)</span><br><span class="hljs-meta">@SpringBootTest</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestSpringBootES</span> </span>&#123;<br><br>    <span class="hljs-meta">@Autowired</span><br>    <span class="hljs-keyword">private</span> ElasticsearchTemplate elasticsearchTemplate;<br><br>    <span class="hljs-meta">@Autowired</span><br>    <span class="hljs-keyword">private</span> ItemRepository itemRepository;<br><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testCreate</span><span class="hljs-params">()</span> </span>&#123;<br>        <span class="hljs-comment">// 创建索引，会根据Item类的@Document注解信息来创建</span><br>        elasticsearchTemplate.createIndex(Item.class);<br>        <span class="hljs-comment">// 配置映射，会根据Item类中的id、Field等字段来自动完成映射</span><br>        elasticsearchTemplate.putMapping(Item.class);<br>    &#125;<br></code></pre></td></tr></table></figure>

<p>使用 <code>kibana</code> 查询</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs routeros"><span class="hljs-builtin-name">GET</span> item<br></code></pre></td></tr></table></figure>

<p>增删改操作</p>
<p>Spring Data 的强大之处，就在于你不用写任何DAO处理，自动根据方法名或类的信息进行CRUD操作。只要你定义一个接口，然后继承Repository提供的一些子接口，就能具备各种基本的CRUD功能。</p>
<p>编写 ItemRepository</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ItemRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ElasticsearchRepository</span>&lt;<span class="hljs-title">Item</span>,<span class="hljs-title">Long</span>&gt; </span>&#123;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<p>增加</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@RunWith(SpringRunner.class)</span><br><span class="hljs-meta">@SpringBootTest</span><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestSpringBootES</span> </span>&#123;<br><br>    <span class="hljs-meta">@Autowired</span><br>    <span class="hljs-keyword">private</span> ElasticsearchTemplate elasticsearchTemplate;<br><br>    <span class="hljs-meta">@Autowired</span><br>    <span class="hljs-keyword">private</span> ItemRepository itemRepository;<br><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testAdd</span><span class="hljs-params">()</span> </span>&#123;<br>        Item item = <span class="hljs-keyword">new</span> Item(<span class="hljs-number">1L</span>, <span class="hljs-string">&quot;小米手机7&quot;</span>, <span class="hljs-string">&quot; 手机&quot;</span>,<br>                <span class="hljs-string">&quot;小米&quot;</span>, <span class="hljs-number">3499.00</span>, <span class="hljs-string">&quot;http://image.leyou.com/13123.jpg&quot;</span>);<br>        itemRepository.save(item);<br>    &#125;<br><br>&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs routeros"><span class="hljs-builtin-name">GET</span> item/_search<br></code></pre></td></tr></table></figure>

<p>修改(id存在就是修改，否则就是插入)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testUpdate</span><span class="hljs-params">()</span> </span>&#123;<br>    Item item = <span class="hljs-keyword">new</span> Item(<span class="hljs-number">1L</span>, <span class="hljs-string">&quot;小米手机7777&quot;</span>, <span class="hljs-string">&quot; 手机&quot;</span>,<br>                         <span class="hljs-string">&quot;小米&quot;</span>, <span class="hljs-number">9499.00</span>, <span class="hljs-string">&quot;http://image.leyou.com/13123.jpg&quot;</span>);<br>    itemRepository.save(item);<br>&#125;<br>GET item/_search<br></code></pre></td></tr></table></figure>

<p>批量新增</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"> <span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">indexList</span><span class="hljs-params">()</span> </span>&#123;<br>        List&lt;Item&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>        list.add(<span class="hljs-keyword">new</span> Item(<span class="hljs-number">2L</span>, <span class="hljs-string">&quot;坚果手机R1&quot;</span>, <span class="hljs-string">&quot; 手机&quot;</span>, <span class="hljs-string">&quot;锤子&quot;</span>, <span class="hljs-number">3699.00</span>, <span class="hljs-string">&quot;http://image.leyou.com/123.jpg&quot;</span>));<br>        list.add(<span class="hljs-keyword">new</span> Item(<span class="hljs-number">3L</span>, <span class="hljs-string">&quot;华为META10&quot;</span>, <span class="hljs-string">&quot; 手机&quot;</span>, <span class="hljs-string">&quot;华为&quot;</span>, <span class="hljs-number">4499.00</span>, <span class="hljs-string">&quot;http://image.leyou.com/3.jpg&quot;</span>));<br>        <span class="hljs-comment">// 接收对象集合，实现批量新增</span><br>        itemRepository.saveAll(list);<br>    &#125;<br>GET item/_search<br></code></pre></td></tr></table></figure>

<p>删除操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testDelete</span><span class="hljs-params">()</span> </span>&#123;<br>    itemRepository.deleteById(<span class="hljs-number">1L</span>);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>根据id查询</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testQuery</span><span class="hljs-params">()</span></span>&#123;<br>        Optional&lt;Item&gt; optional = itemRepository.findById(<span class="hljs-number">2L</span>);<br>        System.out.println(optional.get());<br>    &#125;<br></code></pre></td></tr></table></figure>

<p>查询全部，并按照价格降序排序</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testFind</span><span class="hljs-params">()</span></span>&#123;<br>      <span class="hljs-comment">// 查询全部，并按照价格降序排序</span><br>      Iterable&lt;Item&gt; items = <span class="hljs-keyword">this</span>.itemRepository.findAll(Sort.by(Sort.Direction.DESC, <span class="hljs-string">&quot;price&quot;</span>));<br>      items.forEach(item-&gt; System.out.println(item));<br>  &#125;<br></code></pre></td></tr></table></figure>

<p>自定义方法</p>
<p>Spring Data 的另一个强大功能，是根据方法名称自动实现功能。<br>比如：你的方法名叫做：findByTitle，那么它就知道你是根据title查询，然后自动帮你完成，无需写实现类。<br>当然，方法名称要符合一定的约定：</p>
<table>
<thead>
<tr>
<th>Keyword</th>
<th align="left">Sample</th>
<th>Elasticsearch Query String</th>
</tr>
</thead>
<tbody><tr>
<td><code>And</code></td>
<td align="left"><code>findByNameAndPrice</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : [ &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;, &#123;&quot;field&quot; : &#123;&quot;price&quot; : &quot;?&quot;&#125;&#125; ]&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Or</code></td>
<td align="left"><code>findByNameOrPrice</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;should&quot; : [ &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;, &#123;&quot;field&quot; : &#123;&quot;price&quot; : &quot;?&quot;&#125;&#125; ]&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Is</code></td>
<td align="left"><code>findByName</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Not</code></td>
<td align="left"><code>findByNameNot</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must_not&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Between</code></td>
<td align="left"><code>findByPriceBetween</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;range&quot; : &#123;&quot;price&quot; : &#123;&quot;from&quot; : ?,&quot;to&quot; : ?,&quot;include_lower&quot; : true,&quot;include_upper&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>LessThanEqual</code></td>
<td align="left"><code>findByPriceLessThan</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;range&quot; : &#123;&quot;price&quot; : &#123;&quot;from&quot; : null,&quot;to&quot; : ?,&quot;include_lower&quot; : true,&quot;include_upper&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>GreaterThanEqual</code></td>
<td align="left"><code>findByPriceGreaterThan</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;range&quot; : &#123;&quot;price&quot; : &#123;&quot;from&quot; : ?,&quot;to&quot; : null,&quot;include_lower&quot; : true,&quot;include_upper&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Before</code></td>
<td align="left"><code>findByPriceBefore</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;range&quot; : &#123;&quot;price&quot; : &#123;&quot;from&quot; : null,&quot;to&quot; : ?,&quot;include_lower&quot; : true,&quot;include_upper&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>After</code></td>
<td align="left"><code>findByPriceAfter</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;range&quot; : &#123;&quot;price&quot; : &#123;&quot;from&quot; : ?,&quot;to&quot; : null,&quot;include_lower&quot; : true,&quot;include_upper&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Like</code></td>
<td align="left"><code>findByNameLike</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &#123;&quot;query&quot; : &quot;?*&quot;,&quot;analyze_wildcard&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>StartingWith</code></td>
<td align="left"><code>findByNameStartingWith</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &#123;&quot;query&quot; : &quot;?*&quot;,&quot;analyze_wildcard&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>EndingWith</code></td>
<td align="left"><code>findByNameEndingWith</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &#123;&quot;query&quot; : &quot;*?&quot;,&quot;analyze_wildcard&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Contains/Containing</code></td>
<td align="left"><code>findByNameContaining</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &#123;&quot;query&quot; : &quot;**?**&quot;,&quot;analyze_wildcard&quot; : true&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>In</code></td>
<td align="left"><code>findByNameIn(Collectionnames)</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;bool&quot; : &#123;&quot;should&quot; : [ &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;, &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125; ]&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>NotIn</code></td>
<td align="left"><code>findByNameNotIn(Collectionnames)</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must_not&quot; : &#123;&quot;bool&quot; : &#123;&quot;should&quot; : &#123;&quot;field&quot; : &#123;&quot;name&quot; : &quot;?&quot;&#125;&#125;&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>Near</code></td>
<td align="left"><code>findByStoreNear</code></td>
<td><code>Not Supported Yet !</code></td>
</tr>
<tr>
<td><code>True</code></td>
<td align="left"><code>findByAvailableTrue</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;available&quot; : true&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>False</code></td>
<td align="left"><code>findByAvailableFalse</code></td>
<td><code>&#123;&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;available&quot; : false&#125;&#125;&#125;&#125;</code></td>
</tr>
<tr>
<td><code>OrderBy</code></td>
<td align="left"><code>findByAvailableTrueOrderByNameDesc</code></td>
<td><code>&#123;&quot;sort&quot; : [&#123; &quot;name&quot; : &#123;&quot;order&quot; : &quot;desc&quot;&#125; &#125;],&quot;bool&quot; : &#123;&quot;must&quot; : &#123;&quot;field&quot; : &#123;&quot;available&quot; : true&#125;&#125;&#125;&#125;</code></td>
</tr>
</tbody></table>
<p>例如，我们来按照价格区间查询，定义这样的一个方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">ItemRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ElasticsearchRepository</span>&lt;<span class="hljs-title">Item</span>,<span class="hljs-title">Long</span>&gt; </span>&#123;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 根据价格区间查询</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> price1</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> price2</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-function">List&lt;Item&gt; <span class="hljs-title">findByPriceBetween</span><span class="hljs-params">(<span class="hljs-keyword">double</span> price1, <span class="hljs-keyword">double</span> price2)</span></span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>然后添加一些测试数据：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">indexList</span><span class="hljs-params">()</span> </span>&#123;<br>    List&lt;Item&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>    list.add(<span class="hljs-keyword">new</span> Item(<span class="hljs-number">1L</span>, <span class="hljs-string">&quot;小米手机7&quot;</span>, <span class="hljs-string">&quot;手机&quot;</span>, <span class="hljs-string">&quot;小米&quot;</span>, <span class="hljs-number">3299.00</span>, <span class="hljs-string">&quot;http://image.leyou.com/13123.jpg&quot;</span>));<br>    list.add(<span class="hljs-keyword">new</span> Item(<span class="hljs-number">2L</span>, <span class="hljs-string">&quot;坚果手机R1&quot;</span>, <span class="hljs-string">&quot;手机&quot;</span>, <span class="hljs-string">&quot;锤子&quot;</span>, <span class="hljs-number">3699.00</span>, <span class="hljs-string">&quot;http://image.leyou.com/13123.jpg&quot;</span>));<br>    list.add(<span class="hljs-keyword">new</span> Item(<span class="hljs-number">3L</span>, <span class="hljs-string">&quot;华为META10&quot;</span>, <span class="hljs-string">&quot;手机&quot;</span>, <span class="hljs-string">&quot;华为&quot;</span>, <span class="hljs-number">4499.00</span>, <span class="hljs-string">&quot;http://image.leyou.com/13123.jpg&quot;</span>));	<br>    list.add(<span class="hljs-keyword">new</span> Item(<span class="hljs-number">4L</span>, <span class="hljs-string">&quot;小米Mix2S&quot;</span>, <span class="hljs-string">&quot;手机&quot;</span>, <span class="hljs-string">&quot;小米&quot;</span>, <span class="hljs-number">4299.00</span>, <span class="hljs-string">&quot;http://image.leyou.com/13123.jpg&quot;</span>));<br>    list.add(<span class="hljs-keyword">new</span> Item(<span class="hljs-number">5L</span>, <span class="hljs-string">&quot;荣耀V10&quot;</span>, <span class="hljs-string">&quot;手机&quot;</span>, <span class="hljs-string">&quot;华为&quot;</span>, <span class="hljs-number">2799.00</span>, <span class="hljs-string">&quot;http://image.leyou.com/13123.jpg&quot;</span>));<br>    <span class="hljs-comment">// 接收对象集合，实现批量新增</span><br>    itemRepository.saveAll(list);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>不需要写实现类，然后我们直接去运行：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Test</span><br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">queryByPriceBetween</span><span class="hljs-params">()</span></span>&#123;<br>        List&lt;Item&gt; list = <span class="hljs-keyword">this</span>.itemRepository.findByPriceBetween(<span class="hljs-number">2000.00</span>, <span class="hljs-number">3500.00</span>);<br>        <span class="hljs-keyword">for</span> (Item item : list) &#123;<br>            System.out.println(<span class="hljs-string">&quot;item = &quot;</span> + item);<br>        &#125;<br>    &#125;<br></code></pre></td></tr></table></figure>

<p>虽然基本查询和自定义方法已经很强大了，但是如果是复杂查询（模糊、通配符、词条查询等）就显得力不从心了。此时，我们只能使用原生查询。</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/elasticsearch/">elasticsearch</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/elasticsearch/">elasticsearch</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客目前大部分文章都是参考尚硅谷或者马士兵教育的学习资料！<a href="http://www.atguigu.com/" rel="nofollow noopener"官网地址！</a> 
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/01/13/DistributedTransaction/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">分布式事务</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/01/08/SpringSecurity/">
                        <span class="hidden-mobile">SpringSecurity</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                

              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">

  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
	<!--《添加网站运行时间 -->
<br/>

<span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>
<script>
var now = new Date(); 

function createtime() {
    //此处修改你的建站时间或者网站上线时间
    var grt = new Date('11/02/2021 21:39:00');
    now.setTime(now.getTime() + 250);
    days = (now - grt) / 1000 / 60 / 60 / 24;

    dnum = Math.floor(days);
    hours = (now - grt) / 1000 / 60 / 60 - (24 * dnum);
    hnum = Math.floor(hours);
    if (String(hnum).length == 1) {
        hnum = "0" + hnum;
    }
    minutes = (now - grt) / 1000 / 60 - (24 * 60 * dnum) - (60 * hnum);
    mnum = Math.floor(minutes);
    if (String(mnum).length == 1) {
        mnum = "0" + mnum;
    }
    seconds = (now - grt) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
    snum = Math.round(seconds);
    if (String(snum).length == 1) {
        snum = "0" + snum;
    }
    document.getElementById("timeDate").innerHTML = " 本站已各种夹缝中安全运行 " + dnum + " 天 ";
    document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒";
}
setInterval("createtime()", 250);
</script>

<!-- 添加网站运行时间》-->
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
